package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.base.RecycleViewDivider;
import com.wnhz.work.yz.bean.ErciBean;
import com.wnhz.work.yz.bean.YanShouDaiDetailsBean;
import com.wnhz.work.yz.bean.Yasd;
import com.wnhz.work.yz.bean.YscjikhasofiojsBean;
import com.wnhz.work.yz.bean.YscpdBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class YanShou2GaiChanPinActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView recycler;
    private YanShouDaiDetailsBean bean = new YanShouDaiDetailsBean();
    private List<YanShouDaiDetailsBean.InfoEntity> info = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yan_shou_dai_chan_pin);
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("验收产品");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("验收提交");
        submit.setTextSize(12);
        submit.setVisibility(View.VISIBLE);
        submit.setOnClickListener(this);
        bean = (YanShouDaiDetailsBean) getIntent().getSerializableExtra("bean");
        if (bean == null) {
            MyToast("暂无数据");
            return;
        }

        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new GridLayoutManager(this, 2, LinearLayoutManager.VERTICAL, false));
        recycler.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 1, getResources().getColor(R.color.line_color)));
        info = bean.getInfo();
        adapter = new BaseRVAdapter(this, info) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_dai_chanpin;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                //   x.image().bind(holder.getImageView(R.id.img), info.get(position).getImg());
                ImageLoader.getInstance().displayImage(info.get(position).getImg(), holder.getImageView(R.id.img));

                holder.setTextView(R.id.bianhao, "编号：" + info.get(position).getNumber());
                holder.setTextView(R.id.name, info.get(position).getName());
                holder.setTextView(R.id.house, info.get(position).getHouse());
                holder.setTextView(R.id.sku, info.get(position).getInfo());
                if ("0".equals(info.get(position).getStatus())) {
                    holder.setTextView(R.id.status, "未检");
                    holder.getTextView(R.id.status).setTextColor(getResources().getColor(R.color.text102));
                } else if ("1".equals(info.get(position).getStatus())) {
                    holder.setTextView(R.id.status, "不合格");
                    holder.getTextView(R.id.status).setTextColor(getResources().getColor(R.color.red));
                } else if ("2".equals(info.get(position).getStatus())) {
                    holder.setTextView(R.id.status, "已通过");
                    holder.getTextView(R.id.status).setTextColor(getResources().getColor(R.color.main_color));
                }
                holder.getView(R.id.ll_max).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("1".equals(info.get(position).getType())) {
                            gotoJian(Integer.parseInt(info.get(position).getStatus()), info.get(position).getPid(), info.get(position).getType());
                        } else {
                            getDetails(position, info.get(position).getHouse());
                        }
                    }
                });
            }
        };
        recycler.setAdapter(adapter);
    }

    BaseRVAdapter adapter;

    private void getDetails(final int position, final String house) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("pid", info.get(position).getPid());
        showDialog();

        XUtil.Post(Url.DECORATE_WAITINGCHECKGOODSDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        YscpdBean bean1 = gson.fromJson(result, YscpdBean.class);

                        startActivityForResult(new Intent(YanShou2GaiChanPinActivity.this, YanShouCPDeActivity.class)
                                .putExtra("bean", bean1)
                                .putExtra("name", bean.getInfo().get(position).getName())
                                .putExtra("position", position + "")
                                .putExtra("house", house + "")
                                .putExtra("score", bean.getInfo().get(position).getScore())
                                .putExtra("company", bean.getInfo().get(position).getCompany()), 999
                        );
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 999 && resultCode == RESULT_OK) {
            try {
                if ("".equals(data.getStringExtra("room_num").trim())) {
                    return;
                }
                info.get(Integer.parseInt(data.getStringExtra("position"))).setHouse(data.getStringExtra("room_num"));
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void gotoJian(final int i, final String s, final String pid) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("pid", s);
        map.put("type", pid);
        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e(i + "----" + key, "" + value + "\n");
            }
        }
        XUtil.Post(Url.DECORATE_CHECKGOODSDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----4"+i, "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        if (i == 0) {
                            YscjikhasofiojsBean bean = gson.fromJson(result, YscjikhasofiojsBean.class);
                            startActivity(new Intent(YanShou2GaiChanPinActivity.this, YanShouLingCiActivity.class)
                                    .putExtra("pid", s).putExtra("type", pid)
                                    .putExtra("bean", bean));
                        } else if (i == 1) {
                            ErciBean bean = gson.fromJson(result, ErciBean.class);
                            startActivity(new Intent(YanShou2GaiChanPinActivity.this, YanShouErCiActivity.class).putExtra("pid", s).putExtra("type", pid)
                                    .putExtra("bean", bean));
                        } else if (i == 2) {
                            Yasd yasd = gson.fromJson(result, Yasd.class);
                            startActivity(new Intent(YanShou2GaiChanPinActivity.this, YanShouYiCiActivity.class).putExtra("bean", yasd));
                        }

                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                upload();
                break;
        }
    }

    private void upload() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        StringBuffer sb = new StringBuffer("[");

        for (int i = 0; i < info.size(); i++) {
            sb.append("{\n" +
                    "            \"pid\":\"" + info.get(i).getPid() + "\",\n" +
                    "            \"room_number\":\"" + info.get(i).getHouse().replace("合同号:", "") + "\"\n" +
                    "            }");
            if (i != info.size() - 1) {
                sb.append(",");
            }

        }
        sb.append("]");

        map.put("json_str", sb);
        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, "" + value + "\n");
            }
        }
        XUtil.Post(Url.DECORATE_ROOMNUMBEROFPACKAGE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        MyToast(info);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });


    }
}
